package com.qushiyun.devops.admin.sync.binlog4j;

import com.gitee.Jmysy.binlog4j.core.BinlogClient;
import com.gitee.Jmysy.binlog4j.core.BinlogClientConfig;
import com.gitee.Jmysy.binlog4j.core.BinlogEvent;
import com.gitee.Jmysy.binlog4j.core.IBinlogClient;
import com.gitee.Jmysy.binlog4j.core.IBinlogEventHandler;
import com.qushiyun.devops.admin.sync.data.mapper.TriggerJobMapper;
import com.qushiyun.devops.admin.sync.data.po.TriggerJob;
import java.util.HashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 实时更新
 *
 * @author zhouzx
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class RealSyncTemplate {

    private final TriggerJobMapper triggerJobMapper;

    private Map<Long, IBinlogClient> clients = new HashMap<>();

    public void start(long id) {
        BinlogClientConfig clientConfig = new BinlogClientConfig();
        TriggerJob job = triggerJobMapper.selectById(id);
        if (job == null) {
            throw new RuntimeException("job不存在！");
        }

        if (job.getStatus() != 0) {
            throw new RuntimeException("job状态不对！");
        }

        clientConfig.setHost("127.0.0.1");
        clientConfig.setPort(3306);
        clientConfig.setUsername("root");
        clientConfig.setPassword("taoren@123");
        clientConfig.setServerId(1990);

        IBinlogClient binlogClient = new BinlogClient(clientConfig);

        binlogClient.registerEventHandler(new IBinlogEventHandler() {

            @Override
            public void onInsert(BinlogEvent event) {
            }

            @Override
            public void onUpdate(BinlogEvent event) {
            }

            @Override
            public void onDelete(BinlogEvent event) {
            }

            @Override
            public boolean isHandle(String s, String s1) {
                return false;
            }

        });

        binlogClient.connect();

    }

    public void stop(long id) {
        IBinlogClient client = clients.get(id);
        if (client != null) {
            client.disconnect();
            clients.remove(id);
        }
    }
}
